package com.qk.management.aop;

import cn.hutool.json.JSONUtil;
import com.qk.common.Result;
import com.qk.common.config.CurrentUserContextHolders;
import com.qk.entity.OperateLog;
import com.qk.management.mapper.OperateLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author kaoM1Jy
 * @date 2025/10/17 18:19
 * @description:
 */
@Slf4j
@Component
@Aspect
@SuppressWarnings("all")
public class LogRecordAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Pointcut("@annotation(com.qk.management.aop.anno.LogAnno)")
    public void pt() {
    }

    @Around("pt()")
    public Object around(ProceedingJoinPoint jpt) {

        Object returnValue = null;

        try {
            long startTime = System.currentTimeMillis();
            returnValue = jpt.proceed();
            long endTime = System.currentTimeMillis();
            Integer UserNameId = CurrentUserContextHolders.get();
            String className = jpt.getClass().getName();
            String methodName = jpt.getSignature().getName();
            Object[] args = jpt.getArgs();
            String params = JSONUtil.toJsonStr(args);
            String result = JSONUtil.toJsonStr(returnValue);
            OperateLog operateLog = OperateLog.builder()
                    .operateUserId(UserNameId)
                    .className(className)
                    .methodName(methodName)
                    .methodParams(params)
                    .returnValue(result)
                    .operateTime(LocalDateTime.now())
                    .costTime(endTime - startTime)
                    .build();
            try {
                operateLogMapper.insert(operateLog);
            } catch (Exception e) {
                log.error("操作日志写入数据库失败:{}", e.getMessage());
            }
        } catch (Throwable e) {
            returnValue = Result.error("您的网络异常，请稍后重试！");
            log.error("操作失败:{}", e.getMessage());
        }

        return returnValue;
    }

}
